package com.xyd.Servlet;

import com.xyd.Biz.Impl.UserLoginBizimpl;
import com.xyd.Biz.UserLoginBiz;
import com.xyd.Entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String name = request.getParameter("userName");
        String pwd = request.getParameter("passWord");

        HttpSession session = request.getSession();
        String CheckCode_session = String.valueOf(session.getAttribute("CHECKCODE_SERVER"));

        //获取到用户输入的验证码
        String code = request.getParameter("veryCode");

        //将用户输入的验证码与session中取出的验证码进行比较，相等的话就进行登录操作不成功则返回得到登录界面
        if (session.getAttribute("checkCode").toString().equalsIgnoreCase(code)) {
            User user = new User();
            user.setUsername(name);
            user.setPwd(pwd);

            UserLoginBiz userLoginBiz = new UserLoginBizimpl();
            User login = userLoginBiz.UserLogin(user);
            if (login != null) {
//                request.setAttribute("login", "登录成功！");


                //登录成功后将用户信息存入session中
                session.setAttribute("user", login);
                response.sendRedirect(request.getContextPath() + "/TodaySpecialsServlet");
            } else {

                response.getWriter().write("<script>alert('用户名或密码错误！');history.go(-1);</script>");
            }
        } else {

            response.getWriter().write("<script>alert('验证码输入错误！');history.go(-1);</script>");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

}




